<?php
/**
 * 
 * @author François Guégnaud
 * @property _url
 * @property _format
 * @property _controller
 * @property _action
 * @method getFormat() & setFormat()
 * @method getController() & setController()
 * @method getAction() & setAction()
 * 
 */
class HackInPain_Engine_Gate extends HackInPain_Singleton_Abstract {

	private static $_url;
	
	/**
	 * Format of the response (null, json, html...)
	 * @var
	 */
	private static $_format = null;
	
	private static $_controller;
	
	private static $_action;

	/**
	 * Rewrite the URL witch structured controller/action/...
	 */
	public function rewriteURL($defaults) {
		//var_dump($_SERVER['REQUEST_URI']);
		// set defaults values
		if(!isset($defaults['format'])) $defaults['format'] = null;
		if(!isset($defaults['controller'])) $defaults['controller'] = 'index';
		if(!isset($defaults['action'])) $defaults['action'] = 'index';
		
		$this->setFormat($defaults['format']);
		$this->setController($defaults['controller']);
		$this->setAction($defaults['action']);
	}
	
	/**
	 * Set format by using $_POST & $_GET
	 * TODO: arranger la recuperation du format de façon a ignorer la position du champs (3)
	 */
	public function setFormat($default) {
		if($this->subrequest(3) == 'format') self::$_format = $this->subrequest(4);
		elseif(isset($_POST['format'])) self::$_format = $_POST['format'];
		else self::$_format = $default;
	}
	
	/**
	 * @return format
	 */
	public function getFormat() {
		return self::$_format;
	}
	
	/**
	 * Set controller by using $_GET
	 */
	public function setController($default) {
		if($this->subrequest(1)!='') self::$_controller = $this->subrequest(1);
		else self::$_controller = $default;
	}
	
	/**
	 * @return controller
	 */
	public function getController() {
		return self::$_controller;
	}
	
	/**
	 * Set action by using $_GET
	 */
	public function setAction($default) {
		if($this->subrequest(2)!='') self::$_action = $this->subrequest(2);
		else self::$_action = $default;
	}
	
	/**
	 * @return action
	 */
	public function getAction() {
		return self::$_action;
	}
	
	/**
	 * Retourne le n-ième argument de l'URL
	 * @return string
	 */
	protected function subrequest($pos) {
		$uri = $_SERVER['REQUEST_URI'];
		$tabUri = explode('/', $uri);
		if(isset($tabUri[$pos])) return $tabUri[$pos];
		else return null;
	}
}